package com.lili.common.handler;

import com.lili.common.ex.LiLiShopException;
import com.lili.common.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandle {


    /**
     * 异常捕获 拦截自定义异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(LiLiShopException.class)
    public Result exception(LiLiShopException exception) {

        exception.printStackTrace();

        return Result.fail().code(exception.getCode()).message(exception.getMsg());
    }


    /**
     * 对绑定异常的处理
     * @param exception
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result exception(BindException exception){
        // 获取到不符合字段的信息
        List<FieldError> fieldErrors = exception.getFieldErrors();

        // 根据字段的名称 和 字段提示的信息收集起来
        Map<String, Object> errorMap = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getRejectedValue));

        return Result.fail(errorMap);
    }

    /**
     * 兜底异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception exception) {

        exception.printStackTrace();
        return Result.fail().message(exception.getMessage());
    }

}
